# -*- coding:utf-8 -*-
from django.db import models
from django.utils.translation import ugettext as _
from django.conf import settings
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.db.models import Q
import datetime
from django.db.models import Sum

class Product(models.Model):
    code = models.CharField(u'код товара', max_length=250)
    name = models.CharField(u'наименование', max_length=250)
    description = models.TextField(u'описание', blank=True, null=True)
    purchase_price = models.FloatField(u'закупочная цена')
    price = models.FloatField(u'цена')
    
    def get_kol(self):
        one = self.movementofgoods_set.filter(receiptofgoods__isnull=False).aggregate(Sum('kol'))['kol__sum'] or 0
        two = self.movementofgoods_set.filter(sale__isnull=False).aggregate(Sum('kol'))['kol__sum'] or 0
        return one - two
    get_kol.short_description = u'количество'
    get_kol.allow_tags = True
    
    class Meta:
        verbose_name = u'товар'
        verbose_name_plural = u'товары'
    
    def __unicode__(self):
        return u'%s - %s (%s руб.)' % (self.code, self.name, self.price)

class MovementOfGoods(models.Model):
    kol = models.IntegerField(u'количество', default=0)
    sum = models.FloatField(u'сумма')
    product = models.ForeignKey(Product, verbose_name = u'товар')
    receiptofgoods = models.ForeignKey('ReceiptOfGoods', verbose_name = u'поступление товара', editable=False, null=True)
    sale = models.ForeignKey('Sale', verbose_name = u'продажа', editable=False, null=True)
    
    class Meta:
        verbose_name = u'движение товара'
        verbose_name_plural = u'движение товара'

class ReceiptAndSaleOfGoods(models.Model):
    datetime = models.DateTimeField(u'дата и время', default=datetime.datetime.now(), editable=True)
    
    def __unicode__(self):
        return '%s' % self.datetime
    
    def get_movementofgoods_str(self):
        result = ''
        for obj in self.movementofgoods_set.all():
            result += u'%s, кол.: %s, на сумму: %s<br/>' % (obj.product, obj.kol, obj.sum)
        return result
    get_movementofgoods_str.short_description = u'товар'
    get_movementofgoods_str.allow_tags = True
    
    def get_sum(self):
        return self.movementofgoods_set.all().aggregate(Sum('sum'))['sum__sum']
    get_sum.short_description = u'сумма'
    get_sum.allow_tags = True
    
    class Meta:
        abstract = True
        
class ReceiptOfGoods(ReceiptAndSaleOfGoods):    
    class Meta:
        verbose_name = u'поступление товара'
        verbose_name_plural = u'поступления товара'
        
class Sale(ReceiptAndSaleOfGoods):
    class Meta:
        verbose_name = u'реализацию товара'
        verbose_name_plural = u'реализация товара'